package com.blog.controller.admin;

import com.blog.entity.User;
import com.blog.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

/**
 * 登录控制器
 */
@Controller
@RequestMapping("/admin")
public class LoginController {

    @Autowired
    private UserService userService;

    @GetMapping({"","login"})
    public String loginPage(){
        //HttpServletRequest request
        //String uri = request.getRequestURI();
        //uri.endsWith("/login")
        return "admin/login";
    }

    //登录检测
    @PostMapping("/login")
    public String login(@RequestParam String username,
                        @RequestParam String password,
                        HttpSession session,
                        RedirectAttributes attributes) {
        User user = userService.checkUser(username,password);
        if(user != null){
            session.setAttribute("user",user);
//            System.out.println("-----===================------:"+user);
            return "admin/index";
        }else{
            attributes.addFlashAttribute("message","用户名或密码有误!!! ");     //将信息添加到缓存中，避免重定向数据丢失
            return "redirect:/admin";
        }
    }

    //退出-注销操作
    @GetMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute("user");
        return "redirect:/admin";
    }

}
